<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="订单编号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入订单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="快递单号" prop="expressNumber">
        <el-input
          v-model="queryParams.expressNumber"
          placeholder="请输入快递单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收货方式" prop="deliveryMethod">
        <el-select v-model="queryParams.deliveryMethod" placeholder="请选择收货方式" clearable size="small">
          <el-option
            v-for="dict in deliveryMethodOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收件人" prop="receiver">
        <el-input
          v-model="queryParams.receiver"
          placeholder="请输入收件人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收件电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入收件电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable size="small">
          <el-option
            v-for="dict in orderStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="标记" prop="orderSign">
        <el-select v-model="queryParams.orderSign" placeholder="请选择标记" clearable size="small">
          <el-option
            v-for="dict in orderSignOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item  label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 340px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" >
      <el-table-column label="订单编号" align="center" prop="orderCode" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <dict-tag v-if="scope.row.orderStatus == '0'" :options="orderStatusOptions" :value="scope.row.orderStatus+''+scope.row.payStatus"/>
          <dict-tag v-else :options="orderStatusOptions" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="订单总金额" align="center" prop="totalAmount" />
      <el-table-column label="收货方式" align="center" prop="deliveryMethod">
        <template slot-scope="scope">
          <dict-tag :options="deliveryMethodOptions" :value="scope.row.deliveryMethod"/>
        </template>
      </el-table-column>
      <el-table-column label="收件人信息" align="center" prop="receiver" >
        <template slot-scope="scope">
          {{scope.row.receiver}}
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateReceiver(scope.row)"
            v-hasPermi="['order:order:edit']"
          >修改</el-button>
          <br>
          {{scope.row.phone}} <br>
          {{scope.row.fullAddress}}
        </template>
      </el-table-column>
      <el-table-column label="标记" align="center" prop="orderSign">
        <template slot-scope="scope">
          <div >
            <span :style="'display: inline-block;height: 12px;width: 12px;background-color: '+colorFormat(scope.row.orderSign)+';border-radius: 50%'"></span>
            <span style="display:inline-block;vertical-align: top">{{signFormat(scope.row.orderSign)}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-in"
            @click="handleSee(scope.row)"
            v-hasPermi="['order:order:edit']"
          >订单详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAddSign(scope.row)"
            v-hasPermi="['order:order:edit']"
          >添加备注</el-button>
          <el-button
            v-if="scope.row.orderStatus == '0' && scope.row.payStatus=='1'"
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleSendGoods(scope.row)"
            v-hasPermi="['order:order:edit']"
          >订单发货</el-button>
          <el-button
            v-if="scope.row.deliveryMethod == '1' && scope.row.orderStatus == '1'"
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleSendGoods(scope.row)"
            v-hasPermi="['order:order:edit']"
          >确认提货</el-button>
          <el-button
            v-if="scope.row.orderStatus == '4'"
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleCancel(scope.row)"
            v-hasPermi="['order:order:edit']"
          >同意取消</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改订单收货人对话框 -->
    <el-dialog :title="title" :visible.sync="receiverEdit" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="收件人" prop="receiver">
              <el-input v-model="form.receiver" placeholder="请输入收件人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收件电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入收件电话" />
            </el-form-item>
          </el-col>
          <div v-if="form.deliveryMethod == '0'">
            <el-col :span="24">
              <el-form-item label="收货地区" prop="selectedArea">
                <el-cascader
                  style="width: 100%"
                  size="large"
                  :options="regionData"
                  v-model="selectedArea"
                  @change="handleCascaderChange">
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="详细地址" prop="address">
                <el-input type="textarea"  :rows="2" v-model="form.address" placeholder="请输入详细地址" />
              </el-form-item>
            </el-col>
          </div>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加备注对话框 -->
    <el-dialog :title="title" :visible.sync="signAdd" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标记:">
          <el-radio-group v-model="form.orderSign">
            <el-radio-button
              v-for="dict in orderSignOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            ><div>
              <div :style="'width: 14px;height: 14px;background-color: '+colorFormat(dict.dictValue)+'; border-radius:75%;margin-right:5px;float: left'"></div>
              {{dict.dictLabel}}
              <i class="el-icon-edit-outline"></i>
            </div>
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="" label-width="0" prop="signRemarks">
          <el-input type="textarea" :rows="5" v-model="form.signRemarks" placeholder="请输入备注内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看订单 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <div>
        <el-row style="margin: 5px 0">
          <el-col :span="4" >订单编号:</el-col>
          <el-col :span="20">{{ form.orderCode }}</el-col>
        </el-row>
        <el-row style="margin: 10px 0">
          <el-col :span="4">收货方式:</el-col>
          <el-col :span="20">
            <dict-tag :options="deliveryMethodOptions" :value="form.deliveryMethod"/>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="4" >收货人:</el-col>
          <el-col :span="20">{{ form.receiver }}</el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="4">联系电话:</el-col>
          <el-col :span="20">{{ form.phone }}</el-col>
        </el-row>
        <el-row style="margin: 5px 0" v-if="form.deliveryMethod == '0'">
          <el-col :span="4">收货地址:</el-col>
          <el-col :span="20">{{form.fullAddress}}</el-col>
        </el-row>
        <el-row style="margin: 5px 0;color: #0099ff">
          <el-col :span="4">用户备注:</el-col>
          <el-col :span="20">{{form.userRemarks}}</el-col>
        </el-row>
        <el-row style="margin: 10px 0">
          <el-col :span="4">订单状态:</el-col>
          <el-col :span="20">
            <dict-tag  :options="orderStatusOptions" :value="form.orderStatus == '0'?form.orderStatus+''+form.payStatus:form.orderStatus"/>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="4">订单信息:</el-col>
          <el-col :span="20">
              <div  v-for="item in form.orderDetailList">
                <div style="display: inline-block;width: 80px;height: 80px"  >
                  <el-image :src="baseUrl+item.picturePath"></el-image>
                </div>
                <div style="display: inline-block;margin-left: 15px;vertical-align: top;width: 280px;">
                  <div style="text-align: left">{{item.goodsCode}}</div>
                  <div style="text-align: left">{{item.goodsName}}</div>
                  <div style="text-align: left">{{unitFormat(item.goodsUnit)}}</div>
                </div>
                <div style="display: inline-block;margin-left: 15px;vertical-align: top;;width: 70px;">
                  <div style="text-align: right">×{{ item.quantity }}</div>
                  <div style="text-align: right">￥{{item.price}}</div>
                </div>
              </div>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="4">优惠金额:</el-col>
          <el-col :span="20" style="text-align: right">￥-{{form.couponAmount}}</el-col>
        </el-row>
        <el-row style="margin: 5px 0" v-if="form.discount">
          <el-col :span="4">活动赠品:</el-col>
          <el-col :span="20" >
            <div  v-for="item in form.discount.giftList">
              <div style="display: inline-block;width: 40px;height: 40px"  >
                <el-image :src="baseUrl+item.picturePath"></el-image>
              </div>
              <div style="display: inline-block;margin-left: 15px;vertical-align: top;width: 350px;">
                <div style="text-align: left">{{item.name}}</div>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0" v-else>
          <el-col :span="4">活动金额:</el-col>
          <el-col :span="20" style="text-align: right">￥-{{form.discountAmount}}</el-col>
        </el-row>
        <el-row style="margin: 5px 0">
        <el-col :span="4">积分抵扣:</el-col>
        <el-col :span="20" style="text-align: right">￥-{{form.integralAmount}}</el-col>
      </el-row>
        <el-row style="margin: 5px 0" v-if="form.deliveryMethod == '0'">
          <el-col :span="4">运费:</el-col>
          <el-col :span="20" style="text-align: right">￥{{form.expressAmount}}</el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="4">支付方式:</el-col>
          <dict-tag  :options="paymentMethodOptions" :value="form.paymentMethod"/>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="4">实收:</el-col>
          <el-col :span="20" style="color: red;font-size: 20px;text-align: right">￥{{form.payTotalAmount}}</el-col>
        </el-row>
        <el-row style="margin: 5px 0" v-if="form.orderSign" >
          <el-col :span="4">标记:</el-col>
          <el-col :span="20" >
            <div>
              <span :style="'display: inline-block;height: 12px;width: 12px;background-color: '+colorFormat(form.orderSign)+';border-radius: 50%'"></span>
              <span style="display:inline-block;vertical-align: top">{{signFormat(form.orderSign)}}</span>
            </div>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0" v-if="form.signRemarks">
          <el-col :span="4">备注信息:</el-col>
          <el-col :span="20" >{{form.signRemarks}}</el-col>
        </el-row>

        <el-row v-if="form.expressCompany && !sendGoods" style="margin: 5px 0">
          <el-col :span="4">快递公司:</el-col>
          <el-col :span="20" >{{form.expressCompany}}</el-col>
        </el-row>
        <el-row v-if="form.expressNumber && !sendGoods" style="margin: 5px 0">
          <el-col :span="4">快递单号:</el-col>
          <el-col :span="20" >{{form.expressNumber}}</el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="4">下单时间:</el-col>
          <el-col :span="20" >{{form.createTime}}</el-col>
        </el-row>
        <el-row style="margin: 5px 0" v-if="form.payTime">
          <el-col :span="4">付款时间:</el-col>
          <el-col :span="20" >{{form.payTime}}</el-col>
        </el-row>
        <el-row style="margin: 5px 0" v-if="form.deliveryTime">
          <el-col :span="4">发货时间:</el-col>
          <el-col :span="20" >{{form.deliveryTime}}</el-col>
        </el-row>
        <el-row style="margin: 5px 0;" v-if="form.finishTime">
          <el-col :span="4">完成时间:</el-col>
          <el-col :span="20" >{{form.finishTime}}</el-col>
        </el-row>
        <el-form v-if="sendGoods" ref="form" :model="form" :rules="rules" style="margin-top: 20px" label-width="80px">
          <el-form-item v-if="form.deliveryMethod == '0'" label="快递公司"  prop="expressCompany">
            <el-input  v-model="form.expressCompany" placeholder="请输入快递公司" />
          </el-form-item>
          <el-form-item v-if="form.deliveryMethod == '0'" label="快递单号"  prop="expressNumber">
            <el-input  v-model="form.expressNumber" placeholder="请输入快递单号" />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" v-if="sendGoods">
        <el-button type="primary" @click="submitSendForm">确定发货</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-else>
        <el-button type="primary" @click="cancel">确 定</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import {listOrder, getOrder, updateOrder, getDetail} from "@/api/order/order";
import { regionData,CodeToText,TextToCode  } from 'element-china-area-data'
import {cancelOrder, sendGoods} from "../../../api/order/order";

export default {
  name: "Order",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      regionData:regionData,
      selectedArea:[],
      areaCodeArray:null,
      // 总条数
      total: 0,
      // 订单管理表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      receiverEdit : false,
      signAdd: false,
      sendGoods :false,
      baseUrl:process.env.VUE_APP_BASE_API,
      dateRange:[],
      // 支付方式：0 微信字典
      paymentMethodOptions: [],
      // 收货方式，0为快递配送，1为上门自提字典
      deliveryMethodOptions: [],
      // 订单状态：0待支付，1待发货，2已发货，3已完成字典
      orderStatusOptions: [],
      // 标记：0红色，1黄色，2绿色，3蓝色，4紫色字典
      orderSignOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        deliveryMethod: null,
        receiver: null,
        phone: null,
        createTime: null,
        orderStatus: null,
        expressNumber: null,
        orderSign: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        expressCompany: [
          { required: true, message: "快递公司不能为空", trigger: "blur" }
        ],
        expressNumber: [
          { required: true, message: "快递单号不能为空", trigger: "change" }
        ],

        receiver: [
          { required: true, message: "收件人不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "收件电话不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "收件地址不能为空", trigger: "blur" }
        ],
        orderSign: [
          { required: true, message: "标记颜色不能为空", trigger: "blur" }
        ],
        signRemarks: [
          { required: true, message: "备注内容不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("payment_method").then(response => {
      this.paymentMethodOptions = response.data;
    });
    this.getDicts("delivery_method").then(response => {
      this.deliveryMethodOptions = response.data;
    });
    this.getDicts("order_status").then(response => {
      this.orderStatusOptions = response.data;
    });
    this.getDicts("order_sign").then(response => {
      this.orderSignOptions = response.data;
    });
  },
  methods: {
    /** 查询订单管理列表 */
    getList() {
      this.loading = true;
      listOrder(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.receiverEdit = false;
      this.signAdd = false;
      this.sendGoods = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        extAppid: null,
        accessToken: null,
        orderCode: null,
        expressAmount: null,
        paymentMethod: null,
        totalAmount: null,
        couponId: null,
        discountAmount: null,
        payAmount: null,
        deliveryMethod: "0",
        receiver: null,
        phone: null,
        address: null,
        userRemarks: null,
        createTime: null,
        payTime: null,
        deliveryTime: null,
        finishTime: null,
        orderStatus: "0",
        expressCompany: null,
        expressNumber: null,
        orderSign: "0",
        signRemarks: null
      };
      this.selectedArea=[];
      this.areaCodeArray=null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleUpdateReceiver(row){
      this.reset();
      getOrder(row.id).then(response => {
        this.form = response.data;
        //处理地址
        let selectedArea = [];
        if (this.form.areaCodeArray) {
          this.areaCodeArray = this.form.areaCodeArray;
          this.form.areaCodeArray.forEach(item=>{
            selectedArea.push(item.value)
          })
          this.selectedArea = selectedArea;
        }
        this.receiverEdit = true;
        this.title = "修改收件人信息";
      });
    },
    handleAddSign(row){
      this.reset();
      getOrder(row.id).then(response => {
        this.form = response.data;
        //处理地址
        let selectedArea = [];
        if (this.form.areaCodeArray) {
          this.areaCodeArray = this.form.areaCodeArray;
          this.form.areaCodeArray.forEach(item=>{
            selectedArea.push(item.value)
          })
          this.selectedArea = selectedArea;
        }
        this.signAdd = true;
        this.title = "备注信息";
      });
    },
    /** 查看订单 */
    handleSee(row) {
      this.reset();
      getDetail(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.sendGoods = false;
        this.title = "订单详情";
      });
    },
    handleSendGoods(row){
      this.reset();
      getDetail(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.sendGoods = true;
        this.title = "订单发货";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.areaCodeArray = this.areaCodeArray;
            updateOrder(this.form).then(response => {
              this.msgSuccess("操作成功");
              this.open = false;
              this.receiverEdit = false;
              this.signAdd = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交按钮 */
    submitSendForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            sendGoods(this.form).then(response => {
              this.msgSuccess("操作成功");
              this.open = false;
              this.sendGoods = false;
              this.getList();
            });
          }
        }
      });
    },
    //取消订单审批
    handleCancel(row){
      const id = row.id;
      this.$confirm('订单取消后将会退款给买家,确定同意吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return cancelOrder(id);
      }).then(() => {
        this.getList();
        this.msgSuccess("订单已取消");
      }).catch(() => {});

    },
    handleCascaderChange(value){
      let aaa = [];
      for (let i = 0; i < value.length; i++) {
        let bb = {};
        bb.value = value[i];
        bb.label = CodeToText[value[i]];
        aaa.push(bb);
      }
      this.areaCodeArray=aaa;
    },
    getTextToCode(textArray) {
      let codeArray = [];
      switch (textArray.length) {
        case 1:
          codeArray[0] = TextToCode[textArray[0]].code;
          break;
        case 2:
          codeArray[0] =TextToCode[textArray[0]].code;
          codeArray[1] =TextToCode[textArray[0]][textArray[1]].code;
          break;
        case 3:
          codeArray[0] =TextToCode[textArray[0]].code;
          codeArray[1] =TextToCode[textArray[0]][textArray[1]].code;
          codeArray[2] =TextToCode[textArray[0]][textArray[1]][textArray[2]].code;
          break;
        default:
          break;
      }
      return codeArray;
    },
    addressFormat(address){
      address=address.replaceAll('/','');
      address=address.replaceAll('-','');
      return address
    },
    colorFormat(value){
      switch (value){
        case '0':
          return 'red'
          break;
        case '1':
          return 'yellow'
          break;
        case '2':
          return 'green'
          break;
        case '3':
          return 'blue'
          break;
        case '4':
          return 'purple'
          break;

        default:
          break;
      }
    },
    signFormat(orderSign) {
      return this.selectDictLabel(this.orderSignOptions, orderSign);
    },
    unitFormat(obj){
      let str = ''
      if(obj){
        let a = Object.values(JSON.parse(obj));
        a.forEach((value,index) => {
          if (index == 0){
            str += value;
          }else {
            str+="/"+value;
          }
        })
      }
      return str;
    },

  }
};
</script>
